package ua.kiev.tosik.price.modules.clients.database.files;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Clients;
import ua.kiev.tosik.price.models.PricesFiles;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PricesFilesUploadWorker extends SwingWorker<PricesFiles, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.files");
	private List<PricesFiles> pricesFilesList;
	private Clients clients;
	private File file = null;
	private Date fileDate = null;
	private IPricesFilesDao pricesFilesDao;

	public PricesFilesUploadWorker() {
		super();
		logger.debug("Initialize PricesFilesUploadWorker");
		try {
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e);
		}
		pricesFilesList = new ArrayList<PricesFiles>();
	}

	public void setClients(Clients clients) {
		this.clients = clients;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileDate(Date fileDate) {
		this.fileDate = fileDate;
	}

	@Override
	protected PricesFiles doInBackground() throws Exception {
		if ( clients == null || pricesFilesDao == null || file == null || fileDate == null ) {
			throw new Exception("Can't upload prices file. Client NULL or Dao NULL or File NULL or FileDate NULL!");
		}
		firePropertyChange("FILE_UPLOAD_START", null, true);
		PricesFiles pricesFiles = new PricesFiles();
		pricesFiles.setClientsId(clients.getId());
		pricesFiles.setFileName(file.getName());
		pricesFiles.setFileSize((int)file.length());
		pricesFiles.setPricesDate(fileDate);
		pricesFiles.setSourceFile(FileUtils.readFileToByteArray(file));
		try {
			pricesFiles = pricesFilesDao.save(pricesFiles);
		} catch (Exception e) {
			logger.error(e);
			throw new Exception(e);
		}
		firePropertyChange("FILE_UPLOAD_DONE", null, true);
		return pricesFiles;
	}

	@Override
	protected void done() {
		super.done();
		try {
			PricesFiles pricesFiles = get();
			firePropertyChange("FILE_UPLOAD_OK", null, pricesFiles);
		} catch (Exception e) {
			logger.error(e);
			firePropertyChange("FILE_UPLOAD_ERROR", null, e);
		}
	}
}
